package top.xia17.plugins.fast.common.utils.web;

import cn.hutool.http.useragent.Browser;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import jakarta.servlet.http.HttpServletRequest;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 请求信息工具
 * @author xia17
 * @date 2020/7/22 14:19
 */
public class RequestUtil {

    private static final String UNKNOWN = "unknown";
    public static final String ERROR_ATTRIBUTE_NAME = "org.springframework.boot.web.servlet.error.DefaultErrorAttributes.ERROR";

    /**
     * 获取ip地址
     * @param request 请求信息
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String comma = ",";
        String localhost = "127.0.0.1";
        if (ip.contains(comma)) {
            ip = ip.split(",")[0];
        }
        if  (localhost.equals(ip))  {
            // 获取本机真正的ip地址
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
        return ip;
    }

    /**
     * 获取浏览器信息
     * @param request /
     * @return /
     */
    public static String getBrowser(HttpServletRequest request){
        UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        Browser browser = userAgent.getBrowser();
        return browser.getName();
    }

    /**
     * 根据ip获取详细地址
     */
    @Deprecated
    public static String getCityInfo(String ip) {
        return "未知";
//        public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp?ip=%s&json=true";
//        String api = String.format(IP_URL,ip);
//        JSONObject object = JSONUtil.parseObj(HttpUtil.get(api));
//        return object.get("addr", String.class);
    }

    /**
     * 添加错误信息
     * @param request 请求
     * @param e 异常
     */
    public static void setErrorAttribute(HttpServletRequest request , Throwable e){
        request.setAttribute(ERROR_ATTRIBUTE_NAME,e);
    }


}
